package android.longs.study.down;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import android.longs.study.base.HomeServlet;
import android.longs.study.base.ResponeModel;


@WebServlet("/down/new/app")
public class DownAppServlte extends HomeServlet{

	@Override
	public void doRequestFunction(HttpServletRequest request,
			HttpServletResponse response) {
		System.out.println(" down new app ");

		try {
		    
		    

			String downUrl = request.getParameter("downUrl");

			String realPath=null;

			if (downUrl!=null&& !downUrl.equals("")) {
				System.out.println("下载文件  路径 为 "+downUrl);
				realPath = this.getServletContext().getRealPath(downUrl);
			}else {
				realPath = this.getServletContext().getRealPath("wisdom_app.apk");

			}
			System.out.println("下载文件  路径 为 "+realPath);


			//下载文件路径 
			String path = realPath;
			//创建文件
			File file = new File(path);
			//设置文件名称
			String filename = file.getName();
			//创建读入流
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			//缓存数组
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			response.reset();
			// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
			response.addHeader("Content-Length", "" + file.length());
			OutputStream os = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			os.write(buffer);// 输出文件
			os.flush();
			os.close();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("异常 "+e.getMessage());
		}

	}

}
